#!/usr/bin/python
# -*- coding: utf-8 -*-

import httplib, urllib
#from plot import *
import wx
from wx import xrc
#import wx.lib.plot as plot
import time
from time import strftime
from datetime import datetime
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as ticker
from matplotlib.dates import strpdate2num,date2num,num2date
import pylab
import numpy as np
import operator
import re

dvzS={}
dvzA={}
Altin={}
imkb={}
alldates={}

def mkdate(trh):
    #return time.strptime(trh,"%d-%m-%Y")
    return datetime.strptime(trh,"%d-%m-%Y")
    

def tcmb(daarr,dvzstr,dbstr):
    #dvzstr='TP.DK.USD.A'
    #global dvzdata
    params = urllib.urlencode(
                              {'cgi': '$ozetweb',
                               #'ARAVERIGRUP': 'bie_dkdovizgn.db',
                               'ARAVERIGRUP': dbstr,
                               'DIL': 'TR',
                               'ONDALIK': 5,
                               'wfmultiple_selection':'ZAMANSERILERI',
                               #'ZAMANSERILERI': 'TP.DK.USD.A', 
                               'ZAMANSERILERI': dvzstr, 
                               'f_begdt': '02-01-2009', 
                               'f_enddt': '09-01-2012',
                               'GRTYPE':1,
                               'FREKANS':7,
                               'YON':1,
                               'GKOD':653996,
                               'SUBMITDEG': 'Rapor'
                               })
    headers = {"Content-type": "application/x-www-form-urlencoded",
                "Accept": "text/plain"}
    conn = httplib.HTTPConnection("evds.tcmb.gov.tr")
    conn.request("POST", "/cgi-bin/famecgi", params, headers)
    response = conn.getresponse()
    #print response.status, response.reason

    html = response.read().decode("iso-8859-9").encode("utf-8")
#    print html


    header,sep,data=html.partition(dvzstr)
    data,sep,tail=data.partition('SEÇİLEN SERİLERİN AÇIKLAMALARI' )

    #print data.encode("utf-8")

    
    
    for l in data.encode("utf-8").split('\n'):
        if l.strip()!="":
            #f re.sub(' +',' ',l)
            trh,bos,dvz=re.sub(' +',' ',l).partition(' ')
#            if dvzstr[-1]=='S':
#                dvzS[mkdate(trh)]=tryfloat(dvz)
#            else:
#                dvzA[mkdate(trh)]=tryfloat(dvz)
            val=tryfloat(dvz)
            #daarr[mkdate(trh)]=tryfloat(dvz) 
            if val>0 :
                daarr[mkdate(trh)]=val



    conn.close()
 


 
def tryfloat(str):
     try:
        return float(str)
     except:
         return 0



def plotlines(plotter):
    global dvzS,dvzA
    # list of (x,y) data point tuples
#    data = [(1,2), (2,3), (3,5), (4,6), (5,8), (6,8), (12,10), (13,4)]
#    data2 = [(2,2), (-3,3), (3,5), (4,-4), (5,6), (6,9), (11,10), (12,4)]
    data=[]
    data2=[]
    data3=[]
    c=0
    #for t in dvzS:
    for t in sorted(dvzS.iterkeys()):
        c+=1
        data.append( [c, dvzS[t]]  )
        data2.append( [c, dvzA[t]]  )
        data3.append([c, (dvzS[t]-dvzA[t])*100+.7 ] )
#        dt=time.strftime("%Y-%m-%d",t)
#        data.append( [dt, dvzS[t]]  )
#        data2.append( [dt, dvzA[t]]  )
#        data3.append([dt, (dvzS[t]-dvzA[t])*100+.7 ] )


    # draw points as a line
    line = plot.PolyLine(data, colour='red', width=1)
    line2 = plot.PolyLine(data2, colour='blue', width=1)
    line3 = plot.PolyLine(data3, colour='green', width=1)
    # also draw markers, default colour is black and size is 2
    # other shapes 'circle', 'cross', 'square', 'dot', 'plus'
    
    marker = plot.PolyMarker(data, marker='plus')
    marker2 = plot.PolyMarker(data2, marker='plus')
    # set up text, axis and draw
    #gc = plot.PlotGraphics([line, marker], 'Line/Marker Graph', 'x axis', 'y axis')
    gc = plot.PlotGraphics([line,line2,line3], 'Line/Marker Graph', 'x axis', 'y axis')
    #gc2 = plot.PlotGraphics([line2], 'Line/Marker Graph', 'x axis', 'y axis')
    plotter.Draw(gc, yAxis=(0,2))
    #plotter.Draw(gc2, xAxis=(0,15), yAxis=(0,15))
    
#def format_date(x, pos=None):
#    thisind = np.clip(int(x+0.5), 0, N-1)
#    return r.date[thisind].strftime('%Y-%m-%d')
 

def mpg_(file):
    global dvzA,dvzS

    dS=[]
    dA=[]
    dAltin=[]
    for t in sorted(dvzS.iterkeys()):
        dS.append(dvzS[t] )
    for t in sorted(dvzA.iterkeys()):
        dA.append(dvzA[t] )

    for t in sorted(Altin.iterkeys()):
        dAltin.append(Altin[t]/100000 )

    
    plt.plot(np.arange(len(dS)), dS,color='r')
    plt.plot(np.arange(len(dA)), dA,color='b')
    plt.plot(np.arange(len(dAltin)), dAltin,color='y')
    plt.show() 


def format_date(x, pos=None):
    #global alldates
    #date = alldates[int(x)]
    date=num2date(int(x))
    #if date.day==1:
    return date.strftime('%m %y')
    if date.month == 1: 
      return date.strftime('%b %Y')
    else: return date.strftime('%b')


def mpg(file):
    global dvzA,dvzS

    dS=[]
    dA=[]
    dSA=[]
    dimkb=[]
    dAltin=[]
    
    dtnumS=[]
    dtnumA=[]
    dtnumSA=[]
    dtnumimkb=[]
    dtnumAltin=[]
    
    for t in sorted(dvzS.iterkeys()):
        dS.append( dvzS[t] )
        dtnumS.append( pylab.date2num(t) )
    for t in sorted(dvzA.iterkeys()):
        dA.append(dvzA[t] )
        dtnumA.append( date2num(t) )

    for t in sorted(dvzS.iterkeys()):
        dSA.append(dvzS[t]-dvzA[t] )
        dtnumSA.append( date2num(t) )


    for t in sorted(Altin.iterkeys()):
        dAltin.append(Altin[t]/1000)
        dtnumAltin.append( date2num(t) )

    for t in sorted(imkb.iterkeys()):
        dimkb.append(imkb[t]/1000)
        dtnumimkb.append( date2num(t) )
    
   
   
    years    = mdates.YearLocator()   # every year
    months   = mdates.MonthLocator()  # every month
    yearsFmt = mdates.DateFormatter('%Y')
   
#    xAxis.set_major_locator(months)
#    #xAxis.set_major_formatter(yearsFmt)
#    #xAxis.set_minor_locator(months)
   
#    xAxis.set_major_formatter(ticker.FuncFormatter(format_date))
    
#    plt.xticks(rotation=50)
#    #fig,ax = plt.subplots(1)
#    #fig.autofmt_xdate()
    
    fig, (ax1,ax2,ax3) = plt.subplots(3, 1, sharex=True)
    
    
    #plt.subplot(211)
    #xAxis = plt.axes().xaxis
    xAxis = ax1.xaxis
    xAxis.set_major_locator(months)
    xAxis.set_major_formatter(ticker.FuncFormatter(format_date))
    
    #ax1.xticks(rotation=50)

    ax1.set_title('usd')
    ax1.plot(dtnumS, dS, color='r')
    ax1.plot(dtnumA, dA, color='b')
    ax1.autoscale(enable=True,axis='y',tight=False)
    #ax2.plot(dtnumSA, dSA, color='y')
    ax2.set_title('imkb')
    ax2.plot(dtnumimkb, dimkb, color='b')
    ax2.autoscale(enable=True,axis='y',tight=False)
    #ax2.subplot(212)
    #xAxis.set_major_locator(months)
    #xAxis.set_major_formatter(ticker.FuncFormatter(format_date))
    #ax2.xticks(rotation=50)
    ax3.set_title('altin')
    ax3.plot(dtnumAltin, dAltin, color='y')
    ax3.autoscale(enable=True,axis='y',tight=False)
    
    fig.autofmt_xdate()
    
    plt.show() 
    #fig.show()




def wrcsv1(daarr,ext):
    f=open('d/'+ strftime('%Y%m%d') + '.'+ext,'w')
    for t in sorted(daarr.iterkeys()):
        f.write(t.strftime( '%Y-%m-%d' ) +";"+ str(daarr[t])+"\n"  )

def wrusd():
    f=open('d/'+ strftime('%Y%m%d') + '.USD','w')
    for t in sorted(dvzS.iterkeys()):
        f.write(t.strftime( '%Y-%m-%d') +";"+ str(dvzS[t])+";"+ str(dvzA[t]) +"\n"  )

def npload(file):
    d=np.loadtxt(file,delimiter=';',
                 #dtype={'names': ('Trh','S','A'), 'formats' : ('S10', 'f8', 'f8')})
                 dtype={'names': ('Trh','S','A'), 'formats' : ('S10', 'f8', 'f8')},
                 converters={0:strpdate2num('%Y-%m-%d')}
                 )
    return d

def joindates():
    t=[]
    t.extend(dvzS.iterkeys())
    t.extend(dvzA.iterkeys())
    t.extend(Altin.iterkeys())
    t=list(set(t))
    return t


if __name__=="__main__":
        
    #dvzstr='TP.DK.USD.A'    
    tcmb(Altin,'TP.MK.T.AOF.Y','bie_mkaltytl.db')
    wrcsv1(Altin,'altin')

    tcmb(imkb,'TP.MK.F.BILESIK','bie_mkbrgn.db')
    wrcsv1(imkb,'imkb')
    
    tcmb(dvzA,'TP.DK.USD.A','bie_dkdovizgn.db')
    tcmb(dvzS,'TP.DK.USD.S','bie_dkdovizgn.db')
    wrusd()
    
    alldates=joindates()
    
    mpg('dvz.csv')


    #npload('dvz.csv')
    
        
#    app=wx.App()
#    app.res=xrc.XmlResource("dvz.xrc")
#    frame = app.res.LoadFrame(None, 'MyFrame1')
#    #frame.Bind(wx.EVT_BUTTON , onCreateCmd, id=xrc.XRCID('btnCreateCmd'))
#    m_panel1=xrc.XRCCTRL(frame, 'm_panel1')
#    plotter = plot.PlotCanvas(m_panel1)

#    plotter.SetInitialSize(size=(900, 400))
#            # enable the zoom feature (drag a box around area of interest)
#    plotter.SetEnableZoom(True)
       
#    #app = wx.PySimpleApp()
#    #f = MyFrame()
#    plotlines(plotter) 
#    #mpg()
#    frame.Show()
#    app.MainLoop()  
      